package com.tchy.cloud.controller;

import com.tchy.cloud.entity.CQQOptionEntity;
import com.tchy.cloud.entity.CQuesQuesEntity;
import com.tchy.cloud.entity.CQuestionnaireEntity;
import org.apache.log4j.Logger;
import org.apache.xerces.impl.dv.dtd.ENTITYDatatypeValidator;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 量表问题
 * xmweilove
 */
@Controller
@RequestMapping("/qqOptionController")
public class CQQOptionController extends BaseController {
    private static final Logger logger = Logger.getLogger(CQQOptionController.class);

    @Autowired
    private CommonService commonService;

    /**
     * 问题选项展示页面跳转
     *
     * @return
     */
    @RequestMapping(params = "index")
    public ModelAndView index(HttpServletRequest request) {
        String qId = request.getParameter("id");
        request.setAttribute("qId", qId);
        return new ModelAndView("clound/qqOption/index");
    }

    /**
     * 问题选项展示数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(CQQOptionEntity cqqOptionEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        String qsId = request.getParameter("qId");
        CriteriaQuery cq = new CriteriaQuery(CQQOptionEntity.class, dataGrid);

        cq.createAlias("questEntity", "as_questEntity");
        cq.eq("as_questEntity.id", Integer.valueOf(qsId));
        cq.eq("deleted", 0);
        cq.addOrder("optionIdentity", SortDirection.asc);
        cq.add();
        // 查询条件组装
        HqlGenerateUtil.installHql(cq, cqqOptionEntity, request.getParameterMap());
        commonService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 新增或编辑页面跳转
     *
     * @param entity
     * @param req
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(CQQOptionEntity entity, HttpServletRequest req) {
        String qsId = req.getParameter("qsId");//问题id
        if (entity.getId() != null) {
            entity = commonService.getEntity(CQQOptionEntity.class, entity.getId());
        } else {
            CQuesQuesEntity questEntity = commonService.getEntity(CQuesQuesEntity.class, Integer.valueOf(qsId));
            entity.setQuestEntity(questEntity);
        }

        req.setAttribute("entity", entity);
        return new ModelAndView("clound/qqOption/addorupdate");
    }
//
//    /**
//     * 明细查看
//     *
//     * @param entity
//     * @param req
//     * @return
//     */
//    @RequestMapping(params = "detail")
//    public ModelAndView detail(CQuestionnaireEntity entity, HttpServletRequest req) {
//        if (entity.getId() != null) {
//            entity = commonService.getEntity(CQuestionnaireEntity.class, entity.getId());
//        }
//        req.setAttribute("entity", entity);
//        return new ModelAndView("clound/quest/detail");
//    }
//
//

    /**
     * 新增及修改的数据处理
     *
     * @param entity
     * @return
     */
    @RequestMapping(params = "saveorupdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveorupdate(CQQOptionEntity entity) {
        AjaxJson j = new AjaxJson();
        entity.setDeleted(0);
        try {
            if (entity.getId() != null) {//修改操作
                CQQOptionEntity obj = commonService.getEntity(CQQOptionEntity.class, entity.getId());
                MyBeanUtils.copyBeanNotNull2Bean(entity, obj);
                commonService.saveOrUpdate(obj);
                j.setMsg("操作成功");
            } else {//保存操作
//                CQuesQuesEntity quesquesEntity = commonService.getEntity(CQuesQuesEntity.class, entity.getQuestEntity().getId());
//                Integer quesType = quesquesEntity.getQuesType();
//                if (quesType == 1 || quesType == 2)
//                    entity.setReplyType(1);
//                else
//                    entity.setReplyType(3);
                commonService.save(entity);
                j.setMsg("操作成功");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }

    /**
     * 验证选项名称是否存在，存在不允许提交
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "checkName")
    @ResponseBody
    public Map<String, String> checkName(HttpServletRequest request) {
        String id = request.getParameter("id");//问题主键
        String name = request.getParameter("name");//问题名称
        String quesId = request.getParameter("quesId");//量表主键
        Map<String, String> map = new HashMap<>();
        try {
            if (id != "") {//修改操作
                CQQOptionEntity entity = commonService.getEntity(CQQOptionEntity.class, Integer.valueOf(id));
                if (!name.equals(entity.getName())) {
                    String sql = "select count(*) num from c_ques_ques_option where name= ? and ques_ques_id=? and ques_ques_option_id !=? and deleted=0";
                    List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name, quesId, Integer.valueOf(id)});
                    Map returnMmap = list.get(0);
                    if (Integer.valueOf(String.valueOf(returnMmap.get("num"))) == 0) {
                        map.put("code", "0");
                        map.put("msg", "success");
                    } else {
                        map.put("code", "1");
                        map.put("msg", "此选项名称已经存在，请更改后重试。");
                    }
                }

            } else {//保存操作
                String sql = "select count(*) num from c_ques_ques_option where name= ? and ques_ques_id=? and deleted=0";
                List<Map<String, Object>> list = commonService.findForJdbc(sql, new Object[]{name, quesId});
                Map returnMmap = list.get(0);
                if (Integer.valueOf(String.valueOf(returnMmap.get("num"))) == 0) {
                    map.put("code", "0");
                    map.put("msg", "success");
                } else {
                    map.put("code", "1");
                    map.put("msg", "此选项名称已经存在，请更改后重试。");
                }

            }
        } catch (Exception e) {
            logger.error(e);
        }
        return map;
    }


    /**
     * 删除操作
     *
     * @param entity
     * @return
     */
    @RequestMapping(params = "del", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson del(CQQOptionEntity entity, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            if (entity.getId() != null) {//修改
                entity = commonService.get(CQQOptionEntity.class, entity.getId());
                if (entity.getDeleted() == 0)
                    entity.setDeleted(1);
                else
                    entity.setDeleted(0);
                commonService.saveOrUpdate(entity);
//                commonService.delete(entity);
                j.setMsg("操作成功");
            } else {
                j.setMsg("问题不存在，请刷新后重试。");
            }
        } catch (Exception e) {
            logger.error(e);
            j.setMsg("操作失败");
        }
        return j;
    }
}
